// Copyright 2008 and onwards Matt Burkhart, Mike Chan.
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.

#include <assert.h>
#include <sys/statvfs.h>

#include "source.h"

using namespace std;

Source::Source(const string& location)
  : location_(location) {
  // We can verify the validity of this location here.
}

unsigned long long Source::GetFreeSpace() const {
  // A better implementation would cache this value. The cache can be dirtied
  // given a notification from the kernel that the underlying file system has
  // been modified.
  struct statvfs drive_buffer;
  assert(!statvfs(location_.c_str(), &drive_buffer));

  return drive_buffer.f_bsize * drive_buffer.f_bavail;
}

bool Source::operator==(const Source& operand) const {
  return location_ == operand.location_;
}

bool Source::operator<(const Source& operand) const {
  // This implementation gives a higher file allocation priority to those
  // sources which have more free space. See allocateSources.
  return GetFreeSpace() > operand.GetFreeSpace();
}

Source::operator const std::string&() const {
  return location_;
}

Source::operator const char*() const {
  // This pointer won't stick around for long... it might be best in the long
  // run to remove this function.
  return location_.c_str();
}
